//
//  EMContactsUtil.m
//  gringotts
//
//  Created by fyc on 2019/2/21.
//  Copyright © 2019 wanda. All rights reserved.
//

#import "EMContactsUtil.h"

@interface EMContactsUtil()

@end

@implementation EMContactsUtil

static id _instance = nil;
+ (instancetype)sharedInstance {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc]init];
    });
    return _instance;
}

/**
 下面方法保证了对象在实现alloc方法或者new方法得到的内存地址和单例的内存地址一致
 */
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

/**
 通过copy创建的对象内存地址和单例内存地址一致
 */
-(id)copyWithZone:(NSZone *)zone
{
    return _instance;
}
/**
 通过mutableCopy创建的对象内存地址和单例内存地址一致
 */
-(id)mutableCopyWithZone:(NSZone *)zone {
    return _instance;
}

- (void)getUserContacts:(void(^)(NSMutableArray<EMContactsModel *> *contacts))success
                 failed:(void(^)(NSError *error,CNAuthorizationStatus status))failed {
    // 1.获取授权状态
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    CNContactStore *store = [CNContactStore new];
    if (status == CNAuthorizationStatusNotDetermined){
        
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (granted){
                    success([self contactStore:store]);
                }else{
                    failed(nil,status);
                }
            });
            
        }];
    }else if (status == CNAuthorizationStatusRestricted) {
        failed(nil,status);
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:NSLocalizedString(@"请在手机设置中允许PinMoney访问，以便快速选择联系人", nil) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"知道了", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:cancel];
        [ICE_ROOT_NAVIGATION_CONTROLLER.topViewController presentViewController:alert animated:YES completion:nil];
    }else if (status == CNAuthorizationStatusDenied){
        failed(nil,status);
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:NSLocalizedString(@"请在手机'设置-隐私-通讯录'中设置，以便快速选择联系人", nil) preferredStyle:UIAlertControllerStyleAlert];
         UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"知道了", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             
         }];
        UIAlertAction *ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"前往设置", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:cancel];
        [alert addAction:ok];
        [ICE_ROOT_NAVIGATION_CONTROLLER.topViewController presentViewController:alert animated:YES completion:nil];
    }else if (status == CNAuthorizationStatusAuthorized){
        
        success([self contactStore:store]);
    }

    
}

- (NSMutableArray<EMContactsModel *> *)contactStore:(CNContactStore *)store{

    NSArray *fetchKeys = @[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey,CNContactOrganizationNameKey,CNContactPostalAddressesKey];
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:fetchKeys];
    // 3.请求联系人
    NSError *error = nil;
    
    NSMutableArray<EMContactsModel *> *addressBookModels = [NSMutableArray new];
    
    [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        EMContactsModel *model = [EMContactsModel contactModelWith:contact];
        if (model) {
            [addressBookModels addObject:model];
        }
    }];
    return addressBookModels;
}

@end

@interface EMContactsModel ()

@end


@implementation EMContactsModel

// 直接添加以下代码即可自动完成
- (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
- (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }
- (id)copyWithZone:(NSZone *)zone { return [self yy_modelCopy]; }
- (NSUInteger)hash { return [self yy_modelHash]; }
- (BOOL)isEqual:(id)object { return [self yy_modelIsEqual:object]; }
- (NSString *)description { return [self yy_modelDescription]; }

+ (NSDictionary<NSString *,id> *)modelContainerPropertyGenericClass
{
    return @{@"contactMobile":[NSString class],
             @"contactAddress":[NSString class],
             @"contactCompanyName":[NSString class]
    };
}

+ (nullable instancetype)contactModelWith:(CNContact *)contact
{
    if (nil == contact)
    {
        return nil;
    }
    
    EMContactsModel *contactModel = [EMContactsModel new];
    //stop决定是否要停
    // 获取姓名
    NSString *familyName = contact.familyName;
    if (familyName == nil) familyName = @"";
    NSString *givenName = contact.givenName;
    if (givenName == nil) givenName = @"";
    NSString *name = [NSString stringWithFormat:@"%@%@", familyName ,givenName];
    
    //一个联系人对应多个电话号码，每个CNPhoneNumber对应一个电话Value
    NSArray *phones = contact.phoneNumbers;
    
    NSMutableArray *phonesArray = [NSMutableArray new];
    //遍历电话号码
    for (CNLabeledValue *labelValue in phones) {
        CNPhoneNumber *phoneNumber = labelValue.value;
        
        NSString *phone = phoneNumber.stringValue;
        phone = [[phone componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
        
        [phonesArray addObject:phone];
        
    }
    //遍历联系地址
    NSMutableArray *addressArray = [NSMutableArray new];
    
    NSArray *postalAddress = contact.postalAddresses;
    
    for (CNLabeledValue * addressValue in postalAddress)
    {
        CNPostalAddress *address = addressValue.value;
        NSString *addressString = [NSString stringWithFormat:@"%@%@%@%@",address.country,address.state,address.city,address.street];
        [addressArray addObject:addressString];
    }
    
    //公司名称
    contactModel.contactCompanyName = contact.organizationName?@[contact.organizationName]:@[@""];
    contactModel.contactName = name;
    contactModel.contactMobile = phonesArray;
    contactModel.contactAddress = addressArray;
    return contactModel;
}

@end
